package org.exmaple.dao;

import org.exmaple.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by zw531 on 2018/1/10. Usage:
 */
@Service
public class UserDaoImpl implements UserDao {
  @Autowired
  private JdbcTemplate jdbcTemplate;

  @Override
  public void saveOneUser(String username, String password) {
    jdbcTemplate.update("insert into USER(username, password) values (?, ?)", username, password);
  }

  @Override
  public void deleteOneUser(Integer id) {
    jdbcTemplate.update("delete from USER where id = ?", id);
  }

  @Override
  public User getOneUser(Integer id) {
    return jdbcTemplate.queryForObject("select * from USER where id = ?", User.class);
  }

  @Override
  public List<User> getAllUsers() {
    List<Map<String, Object>> rows = jdbcTemplate.queryForList("select * from USER");
    Iterator<Map<String, Object>> it = rows.iterator();
    List<User> users = new ArrayList<User>();

    Map<String, Object> userMap = null;

    while (it.hasNext()) {
      User user = new User();
      userMap = it.next();

      user.setId((Integer) userMap.get("id"));
      user.setUsername((String) userMap.get("username"));
      user.setPassword((String) userMap.get("password"));

      users.add(user);
    }

    return users;
  }

  @Override
  public void createTable() {
    jdbcTemplate.execute(
        "create table USER("
            + "id int auto_increment,"
            + "username varchar(64),"
            + "password varchar(64)"
            + ");");
  }
}
